<%@ page contentType="text/html;charset=UTF-8"%>
<%@ include file="/common/taglibs.jsp"%>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta name="menu" content="assetMenu" />
<meta name="nav" content="0" />
<meta name="acc" content="_projectinfo" />
<title>原材料检测</title>
<%@ include file="/common/extjs.jsp"%>
<script type="text/javascript"
	src="<c:url value='/ext/plugin/FieldTip.js'/>" charset="utf-8"></script>
<style>
<!--
.noEditColor {
	background: #CCCCCC;
}
-->
</style>
<script type="text/javascript">
var  app ={};
Ext.onReady(function(){
 Ext.QuickTips.init();
 	var fm = Ext.form;
    var cm = new Ext.grid.ColumnModel({
    	columns:[
    	new Ext.grid.RowNumberer({header:'序号',width: 70}),
    	{
    		header:'检测类型',
    	 	dataIndex: 'kind',
    	 	editor:true,
            width: 120
    	}
    	,{
    		header:'原材料',
    	 	dataIndex: 'name',
    	 	editor:true,
            width: 120
    	},
    	{
    		header:'品牌',
    	 	dataIndex: 'brand',
    	 	editor:true,
            width: 120
    	},{
    		header:'产地',
    	 	dataIndex: 'origin',
    	 	editor:true,
            width: 90
    	},
    	{
    		header:'施工（进场）日期',
    		dataIndex: 'constructiondate',
            width:150,
            renderer:Jinyi.project.Format.formatDateRenderer,
            editor:new  Ext.form.DateField({
            	format :"Y-m-d",
            	maxValue:new Date()
            })
    	},{
    		header:'施工（进场）数量',
    	 	dataIndex: 'constructionnumber',
    	 	editor:new  Ext.form.NumberField({
    	 		minValue:0,
    	 		minTest:"不得小于0!",
    	 		decimalPrecision:0
            }),
            width: 150
    	},
    	{
    		header:'检测项目',
    	 	dataIndex: 'item',
    	 	editor:true,
            width: 90
    	},{
    		header:'检测数',
    	 	dataIndex: 'count',
            width: 90,
        	editor:new  Ext.form.NumberField({
    	 		minValue:0,
    	 		minTest:"不得小于0!",
    	 		decimalPrecision:0
            })
    	},{
    		header:'合格数',
    	 	dataIndex: 'pass',
            width: 90,
        	editor:new  Ext.form.NumberField({
    	 		minValue:0,
    	 		minTest:"不得小于0!",
    	 		decimalPrecision:0
            })
    	},{
    		header:'合格率',
    	 	dataIndex: 'conYield',
    	 	renderer:Jinyi.project.Format.percentRenderer,
            width: 90
    	},{
    		header:'试验检测机构名称',
    	 	dataIndex: 'checkorg',
    	 	editor:true,
            width: 150     
    	},{
    		header:'检测日期',
    		dataIndex: 'checkdate',
    	 	renderer:Jinyi.project.Format.formatDateRenderer,
    	 	editor:new  Ext.form.DateField({
            	format :"Y-m-d",
            	maxValue:new Date()
            }),
            width: 90
    	},{
    		header:'报告编号',
    	 	dataIndex: 'reportnum',
    	 	editor:true,
            width: 90     
    	},{
    		header:'检测结果',   		
    	 	dataIndex: 'checkresult',
    	 	editor:true,
            width: 90
    	},{
    		header:'',
    	 	dataIndex: 'id',
    	 	hidden : true,
            width: 1
    	}],
    	defaults : {
    		align : 'center',
            sortable: true    
        },	
        isCellEditable: function(col, row) {
    	//	var record = store.getAt(row);
    		return Ext.grid.ColumnModel.prototype.isCellEditable.call(this, col, row);
  		}
    });

    
    function fullName(v, record){
        return (Date.parseDate(v, 'Y-m-d'));
    }

    var Record = new Ext.data.Record.create([  
      	  	{name:'id',type:'string'},
      	  	{name:'pid',type:'string'},//工程ID
      	  	{name:'sid',type:'string'},  //合同段Id
      	  	{name:'kind',type:'string'},
      	  	{name:'name',type:'string'},  
      	  	{name:'brand',type:'string'},
      	  	{name:'origin',type:'string'},
       	  	{name:'constructiondate',type:'date',convert: fullName},  
       		{name:'constructionnumber',type:'int'}, 
       		{name:'item',type:'string'},  
       		{name:'planTotal',type:'float'},   
       		{name:'count',type:'float'},  
       	    {name:'pass',type:'float'},
       	 	{name:'conYield',type:'float'},
       		{name:'checkorg',type:'string'},  
    		{name:'checkdate',type:'date',convert: fullName},   
    		{name:'reportnum',type:'string'},  
    		{name:'checkresult',type:'string'},   
    	    {name:'attachment',type:'string'},
    	    {name:'batch',type:'string'},
    	    {name:'remark',type:'string'},
    	    {name:'delFlag',type:'string'}
      ]);
    
              var store =new  Ext.data.Store({
            		url: appConfig.contPath + '/report/materialcheck.action',
            		baseParams :{
            				projectId : '${param.projectId}'
            					},
                 	    reader: new Ext.data.JsonReader({
                  		totalProperty: 'totalCounts',
                       	root: 'results',
                       	id: 'id'
                     }, Record)
            });
              
            	var conSignCombo = new fm.ComboBox({
                    typeAhead: true,
                    triggerAction: 'all',
                    transform:'conSign',
                    lazyRender:true,
                    listClass: 'x-combo-list-small',
                    allowBlank: true,
                    width :100,
                    selectOnFocus : true,
                    listeners : {
                    	select : function(combo,record,index ){  
                    		store.removeAll();
                    		Ext.getCmp("batchCombo").clearValue();
                    		
                    		batchStore.baseParams.conSignId = combo.getValue();
                    		batchStore.load();
                    	}
                    }
                })
                      	
                      	var  batchStore =new Ext.data.JsonStore({  //合同段批次Store
                      		url: appConfig.contPath + '/report/materialcheck!getBatch.action',
                      		baseParams :{
                      			conSignId:conSignCombo.getValue()
                      		},	
                      		root: 'results', 
                      		fields:['value', 'label']	
                      	 });
                      	
                      	var batchCombo = new Ext.form.ComboBox({   //合同段批次combo
                      				typeAhead: false,
                                     triggerAction: 'all',
                                     lazyRender:false,
                                     editor:true,
                                     id:"batchCombo",
                                     listClass: 'x-combo-list-small',
                                     store: batchStore,
                                      mode:'remote',
                                      beforeBlur: Ext.emptyFn,
                                      triggerAction:'all',
                                      hideOnSelect:false,
                                      forceSelection : true,   
                                      selectOnFocus : true,
                                      valueField:'value',
                                      displayField:'label',
                                      triggerAction : 'all',   
                                      typeAhead : true,
                                      width :100,
                                      listeners : {
                                      	select : function(combo,record,index ){                	           		
                                      		store.baseParams.batch =combo.getValue();
                                      		store.baseParams.conSignId =conSignCombo.getValue();
                                      		store.load();
                                      	}
                                      }
                      	});
                      	
                      	function updateRow(batch){
                        		 var Plant = grid.getStore().recordType;
                                 var p = new Plant({
	                      			batch:batch
                                 });
                                 grid.stopEditing();
                                 store.insert(0, p);
                                 grid.startEditing(0, 1);
                       		}
                        
                      	//追加
                      	function repairRow(){
                      		if(""!=batchCombo.getValue()){
                      			updateRow(batchCombo.getValue());
                      			return ;
                      		}
                      		Ext.example.msg('信息', '请选择批次!');
                      	}
                      	//新增
                      	function addRow(){
                      		store.removeAll();
                      		Ext.getCmp("batchCombo").clearValue();
                      		updateRow('');
                      	}
                        
                      	var grid =new  Ext.grid.EditorGridPanel({
                      		cm: cm,
                            iconCls:'grid-columns-icon',
                      		frame:true,
                      		store: store,
                      		clicksToEdit: 1,
                      		title : "原材料检测",
                      		stripeRows: true,	
                      		listeners: {
                              	render: function(g) {    	
                              	  		//searchData();	 	
                              	},
                              	afteredit : function(e){
                              		var record = e.record;
                              		
                              		switch(e.field){
                              		 case 'count': 
                              		 case 'pass': {
                              			var count = record.get("count");
                                  		var pass = record.get("pass");
                                  		if(pass>count){
                                  			record.set("pass",count);
                                  			pass = count;
                                  		}
                                  		
                                  		conYield = pass/count;
                                  		record.set("conYield",conYield);
                                  		break;	                              			 
                              		 }                           		
                              		}
                              	},
                              	delay: 10
                            	},
                      		sm:	new Ext.grid.RowSelectionModel({singleSelect:true}),
                      		region : 'center',
                              loadMask:{msg :'数据加载中...'}, 
                              tbar:[
                      				'合同段：',
                      				conSignCombo,
                      				'批次',
                      				batchCombo,
                                    	'->',
                         		   		{text: '刷新',handler:searchData,iconCls:'dt_flush'},'->',
                      		   		{text: '新增',handler:addRow,iconCls:'dt_flush'},'->',
                      		   		{text: '追加',handler:repairRow,iconCls:'dt_flush'},'->',
                         		   		{text: '删除',handler:deleteRow,iconCls:'dt_flush'},'->',
                          		   	"->",
                         		   		{text: '导出',handler:function(){exportExcelF(grid,"原材料检测")} ,iconCls:'bt_excel'}
                      			],
                              bbar:[	
                      				{text: '保存',handler:saveMoreData,iconCls:'bt_excel'}
                      		]
                      	});
                      	var viewport = new Ext.Viewport({
                          layout: 'border',    
                          items: [grid]
                          }); 
                          
                      /**
                      刷新纪录
                      */
                      function reloadData(){
                      	store.removeAll();
                      	store.load({});
                      }

                      /**
                      查询纪录
                      */
                      function searchData(){
                      	reloadData();
                      }

                      /**
                       * 删除记录
                       */
                       	function deleteRow(){
                      	 var record=grid.selModel.getSelected();
                      	   	if(record ==''||record==null){
                      	 	 	Ext.Msg.show({title: '没有选择项',msg: '请至少选择一项',modal: true,
                      	                	 icon: Ext.Msg.INFO,buttons: Ext.Msg.OK}); return ;}
                      	    Ext.Msg.confirm('删除操作', '删除将无法恢复,是否继续?', function(btn, text){
                      	 
                      	    	if (btn == 'yes'){              	 
                      		    var dataId = record.get("id");
                      		    if(Ext.isEmpty(dataId)){
                      		    	store.remove(record);  
                      			    return;
                      		    } 
                      		   	// 数据库操作
                      		   	Ext.Ajax.request({
                      	        url: appConfig.contPath + '/report/materialcheck!delete.action',
                      	        params:{
                      	         	id: dataId,
                      	    		mode:'json'
                      	        },
                      	         method:'POST',
                      	         success: function(response, options){
                      	        	 try {
                      						var responseData = Ext.decode(response.responseText);
                      	           			if (responseData.success == true) {
                      	           				Ext.getCmp("batchCombo").clearValue();
                      	           				batchStore.load();
                      	           				reloadData();
                      	           	    	 Ext.example.msg('信息', '数据删除成功！');  
                      	            		 } else { Ext.example.msg('提示', '删除失败！');}
                      	            } catch (e) { Ext.example.msg('提示', '删除失败！请稍后再尝试');}
                      	        },
                      	        failure: function(response, options){Ext.example.msg('警告!', '服务端发生错误,数据删除失败!');}
                      	    }); 
                      	  }
                      			}); 			 
                      	 }

                      /**
                       * 保存
                       */
                      function saveMoreData(){
                       	var modified = store.getRange();
                       	var len = modified.length;
                        	
                        	
                        	
                          // 如果没有修改 直接返回
                         	if(len == 0){ Ext.example.msg('信息', '数据没有变动,无须保存！');return;}
                            if(conSignCombo.isValid()){
                            	Ext.example.msg('信息', '请选择合同段！');
                           		return;
                            }
                            Ext.Msg.confirm('保存操作', '请确认数据的正确性,是否继续?', function(btn, text){
                         	 	if(btn == "yes"){
                      		  	var fields = Record.prototype.fields;
                      		  	var jsonData = '[';
                      				for(var i = 0 ,ilen = modified.length; i <　ilen; i++){  
                      					jsonData = jsonData+ '{';
                      					 for(var j = 0, jlen = fields.length; j < jlen; j++){
                      						var f = fields.items[j].name;
                      			            var v = modified[i].get(f);
                      			            if(!Ext.isEmpty(v)) {
                      			               if(Ext.isDate(v)){
                      			                 v= Jinyi.project.Format.formatDateRenderer(v);
                      			               }
                      			          	  jsonData = jsonData +" '" + f +　"' : '" + v +"'";
                      			          	  if(j+1 != jlen) jsonData = jsonData+ ",";
                      			     		}
                      			     	}
                      			     	jsonData = jsonData + '}';
                      			     	var jsonStr = jsonData.substring(jsonData.length-2);
                      			     	if(jsonStr==',}'){
                      			     		jsonData = jsonData.substring(0,jsonData.length-2)+"}";
                      			     	}
                      			     	if(i+1 != ilen) jsonData = jsonData+ ",";
                      		    	}	
                      		    jsonData = jsonData + ']';
                      		  	
                      		    // 数据库操作
                      		    Ext.Ajax.request({
                      		        url:  appConfig.contPath + '/report/materialcheck!save.action',
                      		        params: {
                      		            	jsonStr: jsonData,
                      		            	conSignId:conSignCombo.getValue(),
                      		            	projectId:'${param.projectId}'
                      		        },
                      		        method:'POST',
                      		        success: function(response, options){
                      		           try {
                      						var responseData = Ext.decode(response.responseText);
                      		            	if (responseData.success == true) {
                      			            	searchData();
                      			            	batchStore.load();
                      			                Ext.example.msg('信息', '数据更新成功！');
                      		            		}else { Ext.example.msg('提示', '数据修改失败!'); }
                      								}catch(e) { Ext.example.msg('提示', '修改失败！请稍后再尝试');}
                      		        },
                      		        failure: function(response, options){Ext.example.msg('警告!', '服务端发生错误,数据修改失败!');}
                      		    }); 
                      	 	}
                                });
       }
	                               });
                                  </script>
</head>
<body>
<div style="display: none"><pt:labels type="sign"
	argument1="${param.projectId}" argument2="4" name="conSign"
	default="${conSign}" hasEmpty="false"></pt:labels></div>
</body>